import {Directive, ElementRef, Input, OnDestroy, Renderer2} from '@angular/core';
import {Subscription} from 'rxjs';
import {filter} from 'rxjs/operators';
import {BaseAlcService} from './base-alc.service';
import {ACLCanType} from '@base/types';

@Directive({
    selector: '[baseAlc]',
    exportAs: 'baseAlc',
})
export class BaseAclDirective implements OnDestroy {
    private _value: ACLCanType;
    private change$: Subscription;

    constructor(private el: ElementRef, private renderer: Renderer2, protected srv: BaseAlcService) {
        this.change$ = this.srv.change.pipe(filter(r => r != null)).subscribe(() => this.set(this._value));
    }

    @Input('baseAlc')
    set acl(value: ACLCanType) {
        this.set(value);
    }

    @Input('baseAlc-ability')
    set ability(value: ACLCanType) {
        this.set(this.srv.parseAbility(value));
    }

    ngOnDestroy(): void {
        this.change$.unsubscribe();
    }

    private set(value: ACLCanType): void {
        this._value = value;
        const CLS = 'acl-hide';
        const el = this.el.nativeElement;
        if (this.srv.can(this._value)) {
            this.renderer.removeClass(el, CLS);
        } else {
            this.renderer.addClass(el, CLS);
        }
    }
}